<template>
  <div class="room-age-filter" :style="{ left: `${left}px` }">
    <div class="filter-box">
      <div>
        <svg-icon icon-class="use"></svg-icon>
        建筑用途：
      </div>
      <el-select
        v-model="currentUse"
        :style="{ width: '300px' }"
        clearable
        multiple
        placeholder="建筑用途"
        @change="changeUse"
      >
        <el-option
          v-for="item in useList"
          :key="item.value ? item.value : item"
          :label="item.label ? item.label : item"
          :value="item.value ? item.value : item"
        >
        </el-option>
      </el-select>
    </div>
    <div class="filter-box">
      <div>
        <svg-icon icon-class="structure"></svg-icon>
        建筑结构：
      </div>
      <el-select
        v-model="currentStructure"
        clearable
        :style="{ width: '300px' }"
        multiple
        placeholder="建筑结构"
        @change="changeStructure"
      >
        <el-option
          v-for="item in buildingFilter['structure'].values"
          :key="item.value ? item.value : item"
          :label="item.label ? item.label : item"
          :value="item.value ? item.value : item"
        >
        </el-option>
      </el-select>
    </div>
    <div class="filter-box flex">
      <div>
        <svg-icon icon-class="year"></svg-icon>
        建筑年份：
      </div>
      <el-slider
        class="slider"
        v-model="year"
        v-if="yearSlider"
        range
        show-stops
        :format-tooltip="formatyearTooltip"
        :min="buildingFilter['year'].min"
        :max="buildingFilter['year'].max"
        @change="changeYear"
      >
      </el-slider>
      <span v-if="!yearStartInputVisible" @click="yearTextClick(0)">{{
        year[0]
      }}</span
      ><el-input
        class="year-input"
        v-model.number="year[0]"
        maxlength="4"
        v-else
        @blur="handleYearInputBlur(0)"
        @keyup.enter.native="handleYearInputBlur(0)"
        ref="yearStartInput"
      ></el-input
      >~<span v-if="!yearEndInputVisible" @click="yearTextClick(1)">{{
        year[1]
      }}</span>
      <el-input
        class="year-input"
        v-model.number="year[1]"
        maxlength="4"
        v-else
        @blur="handleYearInputBlur(1)"
        @keyup.enter.native="handleYearInputBlur(1)"
        ref="yearEndInput"
      ></el-input>
    </div>
    <div class="flex">
      <div>
        <svg-icon icon-class="floor"></svg-icon>
        楼层范围：
      </div>
      <div class="flex-start">
        <el-slider
          class="slider"
          v-model="floor"
          v-if="floorSlider"
          range
          show-stops
          :format-tooltip="formatfloorTooltip"
          :max="buildingFilter['floor'].max"
          @change="changeFloor"
        >
        </el-slider>
      </div>
      <span v-if="!floorStartInputVisible" @click="floorTextClick(0)">{{
        floor[0]
      }}</span
      ><el-input
        class="floor-input"
        v-model.number="floor[0]"
        maxlength="4"
        v-else
        @blur="handleFloorInputBlur(0)"
        @keyup.enter.native="handleFloorInputBlur(0)"
        ref="floorStartInput"
      ></el-input
      >~<span v-if="!floorEndInputVisible" @click="floorTextClick(1)">{{
        floor[1]
      }}</span>
      <el-input
        class="floor-input"
        v-model.number="floor[1]"
        maxlength="4"
        v-else
        @blur="handleFloorInputBlur(1)"
        @keyup.enter.native="handleFloorInputBlur(1)"
        ref="floorEndInput"
      ></el-input>
    </div>
    <div class="hr">
      <svg-icon icon-class="area"></svg-icon>
      统计范围：
      <el-button
        v-if="showDrawBtn"
        size="small"
        type="primary"
        @click="handleClickSpaceSearch"
      >
        绘制范围
      </el-button>
      <span v-else>
        当前地图所选择范围
        <el-button type="danger" size="small" @click="handleClearArea"
          >清除</el-button
        >
      </span>
      <div class="prompt">注：若不绘制范围，则统计全部范围内的数据</div>
    </div>
    <div class="flex-center hr">
      <el-button size="small" type="primary" @click="handleStatistics">
        统计
      </el-button>
      <el-button size="small" @click="resetSearch">重置</el-button>
    </div>
    <div class="echart hr" v-if="options">
      <v-chart
        :options="options"
        autoresize
        :style="{ width: '100%', height: '470px' }"
      />
    </div>
    <div class="arrow" @click="handleVisible">
      <i :class="icon"></i>
    </div>
  </div>
</template>

<script>
import { clickSpaceSearch } from '@c/map/components/measure'
import { statistics } from '@/api/user-manager'
import ECharts from 'vue-echarts'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/tooltip'
export default {
  inject: ['map'],
  components: {
    'v-chart': ECharts,
  },
  props: {
    timeLineLayers: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      filterList: [
        {
          label: '大于等于',
          value: 'more',
        },
        {
          label: '小于等于',
          value: 'less',
        },
        {
          label: '建筑用途',
          value: 'use',
        },
        {
          label: '建筑结构',
          value: 'structure',
        },
        {
          label: '楼层大于等于',
          value: 'floorMore',
        },
        {
          label: '楼层小于等于',
          value: 'floorLess',
        },
        {
          label: '建筑年代',
          value: 'decade',
        },
        {
          label: '建筑时间范围',
          value: 'timerRange',
        },
      ],
      useList: [
        '居住',
        '办公',
        '商业',
        '医疗',
        '科教',
        '体育',
        '文化',
        '工业',
        '交通',
        '市政',
        '社福',
        '其他',
      ],
      floor: [0, window.buildingFilter['floor'].max],
      condition: 'more',
      currentUse: [],
      currentStructure: [],
      useFilter: [],
      structureFilter: [],
      floorFilter: [
        'all',
        ['>=', window.buildingFilter['floor'].key, 0],
        [
          '<=',
          window.buildingFilter['floor'].key,
          window.buildingFilter['floor'].max,
        ],
      ],
      yearFilter: [
        'all',
        [
          '>=',
          window.buildingFilter['year'].key,
          window.buildingFilter['year'].min + '年',
        ],
        [
          '<=',
          window.buildingFilter['year'].key,
          window.buildingFilter['year'].max + '年',
        ],
      ],
      buildingFilter: window.buildingFilter,
      currentValue: null,
      year: [
        window.buildingFilter['year'].min,
        window.buildingFilter['year'].max,
      ],
      keys: ['_distance', '_area', '_clickSearch'],
      resultCharts: false,
      resultList: null,
      options: null,
      showDrawBtn: true,
      left: 0,
      icon: 'el-icon-arrow-left',
      yearStartInputVisible: false,
      yearEndInputVisible: false,
      yearSlider: true,
      floorStartInputVisible: false,
      floorEndInputVisible: false,
      floorSlider: true,
    }
  },
  mounted() {},
  methods: {
    handleVisible() {
      console.log('1 :>> ', 1)
      if (!this.left) {
        this.left = -440
        this.icon = 'el-icon-arrow-right'
      } else {
        this.left = 0
        this.icon = 'el-icon-arrow-left'
      }
    },
    handleClickSpaceSearch() {
      if (!this.map._clickSpaceSearch) {
        const layers = this.timeLineLayers
        this.map._clickSpaceSearch = new clickSpaceSearch(
          this.map,
          layers,
          this
        )
        this.map._clickSpaceSearch.init()
      } else {
        this.map._clickSpaceSearch.init()
      }
      this.keys.forEach((i) => {
        if (this.map[i]) {
          this.map[i].destory()
        }
      })
    },
    handleStatistics() {
      let params = {
        floor: this.floor,
        year: this.year,
      }
      if (this.currentStructure.length) {
        params['structure'] = this.currentStructure
      }
      if (
        this.map._clickSpaceSearch &&
        this.map._clickSpaceSearch.lngs.length > 2
      ) {
        params['location'] = this.map._clickSpaceSearch.lngs
      }
      this.setfilter()
      statistics(params).then((res) => {
        console.log('res :>> ', res)
        let arr = [
          { name: '居住', count: 0, sum: 0 },
          { name: '办公', count: 0, sum: 0 },
          { name: '商业', count: 0, sum: 0 },
          { name: '医疗', count: 0, sum: 0 },
          { name: '科教', count: 0, sum: 0 },
          { name: '体育', count: 0, sum: 0 },
          { name: '文化', count: 0, sum: 0 },
          { name: '工业', count: 0, sum: 0 },
          { name: '交通', count: 0, sum: 0 },
          { name: '市政', count: 0, sum: 0 },
          { name: '社福', count: 0, sum: 0 },
          { name: '其他', count: 0, sum: 0 },
        ]
        let timeLineIndex = [
          '居住',
          '办公',
          '商业',
          '医疗',
          '科教',
          '体育',
          '文化',
          '工业',
          '交通',
          '市政',
          '社福',
          '其他',
        ]
        res.forEach((i) => {
          arr.splice(timeLineIndex.indexOf(i.name), 1, i)
        })
        res = arr
        if (this.currentUse.length) {
          res = res.filter((i) => this.currentUse.includes(i.name))
        }
        let data = res.map((i) => i.name).reverse()
        let count = res.map((i) => i.count).reverse()
        let arae = res
          .map((i) => (Number(i.sum) / 1000000).toFixed(2))
          .reverse()
        let options = {
          data,
          count,
          arae,
          maxCount: Math.max(...count),
          maxArea: Math.max(...arae),
        }
        console.log('options :>> ', options)
        this.setEharts(options)
      })
    },
    yearTextClick(index) {
      !index
        ? (this.yearStartInputVisible = true)
        : (this.yearEndInputVisible = true)
      this.$nextTick(() => {
        !index
          ? this.$refs['yearStartInput'].focus()
          : this.$refs['yearEndInput'].focus()
      })
    },
    floorTextClick(index) {
      !index
        ? (this.floorStartInputVisible = true)
        : (this.floorEndInputVisible = true)
      this.$nextTick(() => {
        !index
          ? this.$refs['floorStartInput'].focus()
          : this.$refs['floorEndInput'].focus()
      })
    },
    handleFloorInputBlur(index) {
      console.log('1 :>> ', 1)
      if (!index) {
        if (this.floor[0] < this.buildingFilter['floor'].min) {
          this.$message.error(
            `请输入正确的楼层(${this.buildingFilter['floor'].min}~${this.buildingFilter['floor'].max})`
          )
          return
        }
      } else {
        if (this.floor[1] > this.buildingFilter['floor'].max) {
          this.$message.error(
            `请输入正确的楼层(${this.buildingFilter['floor'].min}~${this.buildingFilter['floor'].max})`
          )
          return
        }
      }
      if (this.floor[0] > this.floor[1]) {
        this.$message.error('请输入正确的楼层,开始楼层不能大于结束楼层')
        return
      }
      !index
        ? (this.floorStartInputVisible = false)
        : (this.floorEndInputVisible = false)
      this.floorSlider = false
      this.$nextTick(() => {
        this.floorSlider = true
        this.changeFloor()
      })
    },
    handleYearInputBlur(index) {
      console.log('1 :>> ', 1)
      if (!index) {
        if (this.year[0] < this.buildingFilter['year'].min) {
          this.$message.error(
            `请输入正确的年份(${this.buildingFilter['year'].min}~${this.buildingFilter['year'].max})`
          )
          return
        }
      } else {
        if (this.year[1] > this.buildingFilter['year'].min) {
          this.$message.error(
            `请输入正确的年份(${this.buildingFilter['year'].max}~${this.buildingFilter['year'].max})`
          )
          return
        }
      }
      if (this.year[0] > this.year[1]) {
        this.$message.error('请输入正确的年份,开始年份不能大于结束年份')
        return
      }
      !index
        ? (this.yearStartInputVisible = false)
        : (this.yearEndInputVisible = false)
      this.yearSlider = false
      this.$nextTick(() => {
        this.yearSlider = true
        this.changeYear()
      })
    },
    setEharts(options) {
      var colors = ['#5470C6', '#91CC75']
      let option = {
        color: colors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          formatter: function (params) {
            var relVal = params[0].name
            for (var i = 0, l = params.length; i < l; i++) {
              relVal +=
                '<br/>' +
                params[i].seriesName +
                ' : ' +
                params[i].value +
                `${params[i].seriesName === '个数' ? '个' : '平方公里'}`
            }
            return relVal
          },
        },
        grid: {},
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        legend: {
          data: ['个数', '面积'],
        },
        yAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true,
            },
            data: options.data,
          },
        ],
        xAxis: [
          {
            type: 'value',
            name: '个数',
            min: 0,
            max: options.maxCount,
            position: 'left',
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[0],
              },
            },
            axisLabel: {
              formatter: '{value}',
            },
          },
          {
            type: 'value',
            name: '面积',
            min: 0,
            max: options.maxArea,
            position: 'right',
            offset: 0,
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[1],
              },
            },
            axisLabel: {
              formatter: '{value}',
            },
          },
        ],
        series: [
          {
            name: '个数',
            type: 'bar',
            data: options.count,
          },
          {
            name: '面积',
            type: 'bar',
            xAxisIndex: 1,
            data: options.arae,
          },
        ],
      }
      this.options = option
    },
    resetSearch() {
      if (this.map._clickSpaceSearch) {
        this.map._clickSpaceSearch.clearArea()
      }
      this.resultCharts = false
      this.resultList = []
      ;(this.year = [
        window.buildingFilter['year'].min,
        window.buildingFilter['year'].max,
      ]),
        (this.floor = [0, window.buildingFilter['floor'].max])
      this.currentUse = []
      this.currentStructure = []
      this.options = null
      this.useFilter = []
      this.structureFilter = []
      this.floorFilter = [
        'all',
        ['>=', this.buildingFilter['floor'].key, this.floor[0]],
        ['<=', this.buildingFilter['floor'].key, this.floor[1]],
      ]
      this.yearFilter = [
        [
          'all',
          ['>=', this.buildingFilter['more'].key, `${this.year[0]}年`],
          ['<=', this.buildingFilter['less'].key, `${this.year[1]}年`],
        ],
      ]
      this.setfilter()
    },
    handleClearArea() {
      if (this.map._clickSpaceSearch) {
        this.map._clickSpaceSearch.clearArea()
      }
    },
    formatfloorTooltip(val) {
      return val + '楼'
    },
    formatyearTooltip(val) {
      return val + '年'
    },
    changeYear() {
      this.yearFilter = [
        'all',
        ['>=', this.buildingFilter['more'].key, `${this.year[0]}年`],
        ['<=', this.buildingFilter['less'].key, `${this.year[1]}年`],
      ]
      this.setfilter()
    },
    reset() {
      this.setDefaultFilter()
      if (this.map._clickSearch && this.map._clickSearch.popup) {
        this.map._clickSearch.popup.remove()
      }
    },
    changeUse() {
      if (this.currentUse.length) {
        this.useFilter = [
          ['in', this.buildingFilter['use'].key, ...this.currentUse],
        ]
      } else {
        this.useFilter = []
      }
      this.setfilter()
    },
    changeStructure() {
      if (this.currentStructure.length) {
        this.structureFilter = [
          [
            'in',
            this.buildingFilter['structure'].key,
            ...this.currentStructure,
          ],
        ]
      } else {
        this.structureFilter = []
      }
      this.setfilter()
    },
    changeFloor() {
      this.floorFilter = [
        'all',
        ['>=', this.buildingFilter['floor'].key, this.floor[0]],
        ['<=', this.buildingFilter['floor'].key, this.floor[1]],
      ]
      this.setfilter()
    },
    setfilter() {
      this.timeLineLayers.forEach((layer) => {
        const allFilter = [
          'all',
          layer.filter,
          this.yearFilter,
          ...this.useFilter,
          ...this.structureFilter,
          this.floorFilter,
        ]
        console.log('allFilter :>> ', allFilter)
        this.map.setFilter(layer.id, allFilter)
      })
    },
    setDefaultFilter() {
      this.timeLineLayers.forEach((layer) => {
        this.map.setFilter(layer.id, layer.filter)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.room-age-filter {
  position: absolute;
  top: 20px;
  left: 0px;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  transition: left 1s;
}
.filter-box {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
  .year-range {
    background: rgba(255, 255, 255, 0.8);
  }
}
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 420px;
  .flex-start {
    flex: 1;
  }
  .slider {
    width: 180px;
    padding: 0px 10px;
  }
}
.hr {
  padding-top: 15px;
  border-top: 2px dashed #ccc;
  margin-top: 10px;
}
.prompt {
  font-size: 15px;
  color: #d5191a;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
.flex-center {
  display: flex;
  justify-content: center;
}
.arrow {
  position: absolute;
  right: -24px;
  background: rgba(255, 255, 255, 0.8);
  font-size: 24px;
  border-radius: 0px 50% 50% 0px;
  top: 20px;
  cursor: pointer;
}
.year-input,
.floor-input {
  width: 4em;
  ::v-deep .el-input__inner {
    padding: 0px 0.5em;
  }
}
</style>
